<template>
  <div class="followAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div
      class="search-button"
      v-if="pageType !== 'detail' && pageType !== 'check'"
    >
      <el-button
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="btn save"
        @click="handleAddSave(followFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <!-- @click="handleEndOperation()" -->
      <el-button class="btn back" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon>返回</el-button
      >
    </div>
    <el-form
      :model="followForm"
      ref="followFormRef"
      :rules="queryRules"
      label-width="100px"
      v-enterToNext
      :disabled="pageType === 'detail'"
    >
      <el-tabs
        v-model="followForm.changeType"
        type="border-card"
        @tab-click="handleTabsClick"
      >
        <el-tab-pane label="点位变更" :name="0">
          <el-collapse v-model="activeNames">
            <!-- 基础信息 -->
            <el-collapse-item
              name="1"
              class="transform-down"
              v-if="!contactAddShow && !saleAddShow"
            >
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">变更信息</span>
              </template>
              <div class="follow-info">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="选择点位：" prop="projectTaskDetailId">
                      <el-select
                        filterable
                        style="width: 268px"
                        v-model="followForm.projectTaskDetailId"
                        placeholder="请选择"
                        clearable
                        class="search-select"
                        @change="handlePointChange"
                      >
                        <el-option
                          v-for="dict in pointList"
                          :key="dict.projectTaskDetailId"
                          :label="dict.pointAdd"
                          :value="dict.projectTaskDetailId"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="省市区：" prop="cityId">
                      <el-select
                        filterable
                        style="width: 93px"
                        v-model="followForm.provinceId"
                        placeholder="请选择"
                        clearable
                        class="search-select"
                        @change="handleProvince('province')"
                      >
                        <el-option
                          v-for="dict in provinceList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                      <el-select
                        filterable
                        style="width: 93px; margin: 0 5px"
                        v-model="followForm.cityId"
                        placeholder="请选择"
                        clearable
                        class="search-select"
                        @change="handleProvince('city')"
                      >
                        <el-option
                          v-for="dict in cityList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                      <el-select
                        filterable
                        style="width: 93px"
                        v-model="followForm.zoneId"
                        placeholder="请选择"
                        clearable
                        class="search-select"
                      >
                        <el-option
                          v-for="dict in areaList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="详细地址：" prop="detailAdd">
                      <el-input
                        maxlength="50"
                        style="width: 100%"
                        v-model="followForm.detailAdd"
                        placeholder="请输入"
                        clearable
                        class="search-input"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="点位名称：" prop="pointAdd">
                      <el-input
                        style="width: 268px"
                        maxlength="20"
                        v-model="followForm.pointAdd"
                        placeholder="请输入"
                        clearable
                        class="search-input"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row style="padding-bottom: 10px">
                  <el-col :span="24">
                    <el-form-item label="备注：" prop="changeDetails">
                      <el-input
                      maxlength="2000"
                        style="width: 100%"
                        type="textarea"
                        v-model="followForm.changeDetails"
                        placeholder="请输入详细变更情况"
                        clearable
                      />
                        <!-- class="search-input" -->
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="配件变更" :name="1">
          <el-collapse v-model="activeNames">
            <!-- 基础信息 -->
            <el-collapse-item
              name="1"
              class="transform-down"
              v-if="!contactAddShow && !saleAddShow"
            >
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">变更信息</span>
              </template>
              <div class="follow-info">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="选择点位：" prop="projectTaskDetailId">
                      <el-select
                        filterable
                        style="width: 268px"
                        v-model="followForm.projectTaskDetailId"
                        placeholder="请选择"
                        clearable
                        class="search-select"
                        @change="handlePointChange"
                      >
                        <el-option
                          v-for="dict in pointList"
                          :key="dict.projectTaskDetailId"
                          :label="dict.pointAdd"
                          :value="dict.projectTaskDetailId"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row style="padding-bottom: 10px">
                  <el-col :span="24">
                    <el-form-item label="备注：" prop="changeDetails">
                      <el-input
                      maxlength="2000"
                        style="width: 100%"
                        type="textarea"
                        v-model="followForm.changeDetails"
                        placeholder="请输入详细变更情况"
                        clearable
                      />
                        <!-- class="search-input" -->
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import {
  getEndFollowApi,
  addFollowApi,
  getProjectApi,
} from "@/api/sales/project";
import { getProvinceApi } from "@/api/information/customer";
// getUserListApi,
import { getDeptListApi } from "@/api/information/customer";
import { getUserListApi, workAllotApi } from "@/api/operation/work";
import {
  getPointList,
  projectReturnTaskApi,
  projectSubmitTaskApi,
  projectFileChangeApi,
} from "@/api/operation/project";
import {
  projectAllotTaskApi,
  projectEditAllotTaskApi,
  getUserTaskApi,
  projectTaskDetailApi,
  projectTaskSelfDetailApi,
  taskChangeDetailApi,
  projectFinishApi,
} from "@/api/operation/project";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
  // 更新跟进组件显隐
  "update:followAddShow",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3", "4", "5", "6"]);
// 客户表单引用
const followFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 当前选中用户
const currentUser = ref(null);
// 当前选中任务
const currentTask = ref(null);
// 任务列表
const taskList = ref([]);
// 项目下任务列表
const projectTaskList = ref([]);
// 变更记录
const changeRecordList = ref([]);
// 点位列表
const pointList = ref([]);
// 设备类型
const deviceTypeList = ref([]);
// 新增联系人表单显隐
const contactAddShow = ref(false);
// 联系人操作类型
const operateType = ref("");
// 新增销售列表表单显隐
const saleAddShow = ref(false);
// 联系人表单引用
const contactFormRef = ref();
// 销售表单引用
const saleFormRef = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 销售清单当前索引(编辑销售清单使用)
const tableIndexSec = ref(null);
// 跟进表单引用
const followFormTemplate = {
  changeDetails: "", // 	变更详情
  changeType: 0, // 变更类型/*0：点位变更；1：配件变更；2：设备变更
  cityId: null, // 市
  detailAdd: "", // 详细地址
  deviceName: "", // 	变更后设备名称
  deviceUuid: "", // 	变更后编号
  latitude: "", // 	纬度
  longitude: "", // 	经度
  pointAdd: "", // 	点位名称
  projectId: null, // 项目id
  projectTaskDetailId: null, // 	任务明细ID
  projectTaskId: null, // 	任务ID
  provinceId: null, // 	省
  zoneId: null, // 	区
};
const data = reactive({
  // 跟进表单
  followForm: JSON.parse(JSON.stringify(followFormTemplate)),
  // 联系人表单
  contactForm: {
    name: "",
    phone: "",
    practiceId: null,
    projectId: null,
    remarks: "",
  },
  // 销售清单表单
  saleForm: {
    actualHour: "", // 实际工时
    armedzoneId: null, // 防区id
    armedzoneName: "", // 防区中文
    cityId: null, // 市
    detailAdd: "", // 详细地址
    deviceModel: "", // 	设备型号
    deviceName: "", // 	设备名称
    deviceType: null, // 	设备类型
    deviceTypeName: "", // 	设备类型中文
    deviceUuid: "", // 设备唯一id
    installType: "", // 	安装方式
    ipAddress: "", // IP地址
    manufacturer: "", // 	生产厂家
    pointAdd: "", // 点位地址
    policeOffice: "", // 所属派出所
    policeWay: "", // 民警联系方式
    projectTaskDetailId: null, // 明细id
    propertyName: "", // 物业名称
    propertyWay: "", // 物业联系方式
    provinceId: null, // 	省
    routBrand: "", // 路由器品牌型号
    simCard: "", // SIM卡信息
    suppFileInfoVos1: [], // 现场实地照片
    suppFileInfoVos2: [], // 外包用工合同
    suppFileInfoVos3: [], // 配件清单表
    suppFileInfoVos4: [], // 用电协议
    suppFileInfoVos5: [], // 现场完成照片
    suppFileInfoVos6: [], // 现场设备照片
    suppFileInfoVos7: [], // 物业租赁合同
    zoneId: null, // 区
  },
  // 跟进表单校验规则
  queryRules: {
    detailAdd: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
    pointAdd: [{ required: true, message: "请输入点位名称", trigger: "blur" }],
    changeDetails: [{ required: true, message: "请输入备注", trigger: "blur" }],
    projectTaskDetailId: [
      { required: true, message: "请选择点位", trigger: "change" },
    ],
    cityId: [{ required: true, message: "请选择省市区", trigger: "change" }],
  },
  // 联系人表单校验规则
  queryContactRules: {
    name: [
      { required: true, message: "请输入姓名", trigger: "blur" },
      { min: 1, max: 15, message: "最多可输入15字", trigger: "blur" },
    ],
    phone: [
      { required: true, message: "请输入联系方式", trigger: "blur" },
      { min: 1, max: 11, message: "最多可输入11字", trigger: "blur" },
    ],
  },
  // 销售清单表单校验规则
  querySaleRules: {
    saleCategory: [
      { required: true, message: "请选择销售类目", trigger: "change" },
    ],
    materialId: [
      { required: true, message: "请选择设备名称", trigger: "change" },
    ],
    quantity: [{ required: true, message: "请输入设备数量", trigger: "blur" }],
    brand: [{ required: true, message: "请输入设备品牌", trigger: "blur" }],
  },
  // 用户列表
  userList: [],
  // 部门列表
  deptList: [],
  // 省列表
  provinceList: [],
  // 市列表
  cityList: [],
  // 区列表
  areaList: [],
});
const {
  contactForm,
  saleForm,
  followForm,
  queryRules,
  userList,
  deptList,
  queryContactRules,
  querySaleRules,
  provinceList,
  cityList,
  areaList,
} = toRefs(data);

/**
 * @description: 保存
 * @param {Object} followFormRef 跟进表单引用
 */
const handleAddSave = async (followFormRef) => {
  if (!followFormRef) return;
  await followFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          let res = await projectFileChangeApi(followForm.value);
          if (res.code === 200) {
            emit("update:followAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 处理点位变更
 */
const handlePointChange = (value) => {
  pointList.value.forEach((item) => {
    if (item.projectTaskDetailId === value) {
      followForm.value.projectTaskId = item.projectTaskId;
    }
  });
};

/**
 * @description: tabs切换
 */
const handleTabsClick = () => {
  followForm.value = {
    ...JSON.parse(JSON.stringify(followFormTemplate)),
    projectId: followForm.value.projectId,
  };
};

/**
 * @description: 处理省市区操作
 * @param {String} type 类型
 */
const handleProvince = (type) => {
  switch (type) {
    case "province":
      cityList.value = [];
      areaList.value = [];
      followForm.value.cityId = null;
      followForm.value.zoneId = null;
      getProvinceApi(followForm.value.provinceId).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      break;
    case "city":
      areaList.value = [];
      followForm.value.area = null;
      getProvinceApi(followForm.value.cityId).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
      break;
  }
};

/**
 * @description: 返回
 */
const handleBack = () => {
  ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      emit("update:followAddShow", false);
      followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
    })
    .catch(() => {});
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (row) => {
  await getDict();
  const id = row.projectId;
  // followForm.value.startTime = row.desireStartTime;
  // followForm.value.endTime = row.desireEndTime;
  // followForm.value.workOrderId = row.workOrderId;
  // followForm.value.maintanceTaskName = row.workOrderName;
  try {
    followForm.value.projectId = id;
    // const res = await projectTaskSelfDetailApi(id);
    // projectTaskList.value = res;
    await getPointList(id).then((res) => {
      if (res) {
        pointList.value = res;
      }
    });
  } catch (error) {}
};

/**
 * @description: 字典列表
 */
const getDict = async () => {
  // 省
  await getProvinceApi(1).then((res) => {
    if (res.code === 200) {
      provinceList.value = res.data;
    }
  });
};

onMounted(() => {
  if (props.pageType !== "detail" && props.pageType !== "check") {
    nextTick(() => {
      setTimeout(() => {
        refInput.value.focus();
      }, 800);
    });
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.followAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .follow-info {
    padding: 20px 10px 5px 10px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .follow-detail-info {
    margin-top: 20px;
  }
  .task-box {
    width: 100%;
    background-color: #f8faff;
  }
  .contact-info {
    padding-top: 20px;
  }
  .task {
    width: 1360px;
    height: 50px;
    margin-bottom: 20px;
    display: flex;
    // overflow-x: auto;
    &-item {
      background-color: #dee6ed;
      min-width: 180px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      margin-right: 2px;
      cursor: pointer;
      &:hover {
        // background: #007cef;
        // color: #fff;
      }
      background: #dee6ed;
      color: #333333;
    }
    .task-current {
      background: #007cef;
      color: #fff;
    }
  }
  .people {
    margin-top: 10px;
    &-item {
      margin-right: 10px;
      cursor: pointer;
      text-decoration: underline;
      &:hover {
        color: #007cef;
      }
    }
  }
  .task-number {
    margin-top: 10px;
  }
  .footer-button {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-bottom: 20px;
  }
}
</style>
